<template>
  <div class="parent">
    <div class="title mb-50">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/zhinengyewu/vehicleInfo' }">{{
          $t("vehicleInfo")
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ lib_name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="divider"></div>
    <div class="content">
      <div class="header">
        <el-form inline :model="formData">
          <el-form-item :label="$t('zhuapaijilu.shaixuantiaojian')">
            <el-input
              v-model="formData.fuzzy_key"
              :placeholder="$t('targetSearchTip')"
            />
          </el-form-item>
          <el-form-item>
            <MyButton class="confirm" @click="search">{{
              $t("makeSure2")
            }}</MyButton>
            <MyButton class="add" @click="handleAdd">{{
              $t("addTip")
            }}</MyButton>
            <MyButton
              className="export"
              icon="el-icon-download"
              @click="handleExportAll"
            >
              {{ $t("common.allExport") }}</MyButton
            >
            <MyButton
              className="export"
              icon="el-icon-download"
              @click="handleExport"
            >
              {{ $t("common.export") }}</MyButton
            >
            <MyButton
              className="delete"
              icon="el-icon-delete"
              @click="handleDeleteMultiple"
              >{{ $t("common.multipleDelete") }}</MyButton
            >
            <MyButton class="add">
              <el-checkbox
                v-model="checkedAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
                >{{ $t("common.selectAll") }}</el-checkbox
              ></MyButton
            >
          </el-form-item>
        </el-form>
      </div>
      <MyTable
        ref="multipleTable"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column width="80" type="selection" sortable></el-table-column>
        <el-table-column
          width="180"
          type="index"
          :label="$t('common.order_number')"
          sortable
        ></el-table-column>
        <el-table-column
          prop="vehicle_number"
          :label="$t('vehicle_number')"
          sortable
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="owner_name"
          :label="$t('vehicle_person_name')"
          sortable
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="owner_gender"
          :label="$t('vehicle_pe_gender')"
          sortable
          min-width="180"
        >
          <template slot-scope="{ row }">
            <span>{{ row.owner_gender | formatGender }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          :label="$t('libCrateTime')"
          sortable
          min-width="180"
        ></el-table-column>
        <el-table-column :label="$t('common.operate')" min-width="180">
          <template slot-scope="scope">
            <MyButton
              class="text"
              @click="handleShowDetail(scope.row)"
              type="text"
              size="small"
            >
              {{ $t("common.view") }}
            </MyButton>
            <span class="ml-10 mr-10">|</span>
            <MyButton
              class="text"
              @click="handleEdit(scope.row)"
              type="text"
              size="small"
            >
              {{ $t("common.edit") }}
            </MyButton>
            <span class="ml-10 mr-10">|</span>
            <MyButton
              class="text"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
              >{{ $t("common.delete") }}</MyButton
            >
          </template>
        </el-table-column>
      </MyTable>
      <Pagination
        v-show="total_num > 10"
        :total="total_num"
        :page.sync="pageNumber"
        :limit.sync="qry_len"
        class="pagingStyle"
        @pagination="getList()"
      />
    </div>
    <SingleExportDialog
      :zippasswd.sync="zippasswd"
      @confirm="confirmSingle"
      @cancel="cancelSingle"
      :visible.sync="isSingleExportShow"
      :step="singleStep"
    />
    <MultipleExportDialog
      :zippasswd="zippasswd"
      :num="total_num"
      @confirm="confirmBatch"
      @cancel="cancelBatch"
      :visible.sync="isBatchExportShow"
      :step="batchStep"
    />
    <Detail
      :visible.sync="isDetailShow"
      :row="row"
      @refresh="getList"
      :editType="editType"
      :lib_id="lib_id"
    />
  </div>
</template>

<script>
import MyButton from "@/components/Button";
import {
  getList,
  deleteList,
  exportList,
  exportBatchList,
  deleteSingle,
} from "./service";
import util from "@/utils";
import { validatePwd, downLoadUrl } from "@/services";
import SingleExportDialog from "@/components/SingleExportDialog.vue";
import MultipleExportDialog from "@/components/MultipleExportDialog.vue";
import Pagination from "@/components/Pagination";
import { getStorageTime } from "@/views/storage/service.js";
import Detail from "./DetailEdit";
export default {
  components: {
    MyButton,
    SingleExportDialog,
    MultipleExportDialog,
    Pagination,
    Detail,
  },
  data() {
    return {
      formData: {},
      tableData: [],
      lib_name: "",
      lib_id: "",
      checkedAll: false,
      cardList: [],
      isIndeterminate: false,
      isSingleExportShow: false,
      isBatchExportShow: false,
      zippasswd: "",
      singleStep: 0,
      batchStep: 0,
      isShowBatchUpload: false,
      uploadProgress: 0,
      batchInfo: {
        total: 0,
        err_count: 0,
      },
      fileList: [],
      isDetailShow: false,
      editType: "show",
      row: {},
      qry_len: 50,
      pageNumber: 1,
      total_num: 0,
      selectedList: [],
    };
  },
  watch: {
    selectedList: {
      handler(val) {
        if(val.length === 0) {
          this.checkedAll = false;
          this.isIndeterminate = false;
        } else if(val.length === this.tableData.length) {
          this.checkedAll = true;
          this.isIndeterminate = false;
        } else {
          this.checkedAll = false;
          this.isIndeterminate = true;
        }
      },
      deep: true,
    },
  },
  computed: {
    start_no: {
      get() {
        return 1 + this.qry_len * (this.pageNumber - 1);
      },
    },
  },
  async mounted() {
    const params = this.$route.query;
    if (params) {
      this.lib_name = params.lib_name;
      this.lib_id = Number(params.lib_id);
      await this.getStorageTime();
      this.getList();
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.selectedList = val;
    },
    handleAdd() {
      this.isDetailShow = true;
      this.editType = "add";
      this.row = {};
    },
    search() {
      this.pageNumber = 1;
      this.getList();
    },
    async getStorageTime() {
      const params = {
        store_obj: 1,
      };
      const res = await getStorageTime(params);
      if (res.code == 0) {
        this.saved_time = res.data.saved_time;
      }
      return true;
    },
    handleShowDetail(item) {
      // 显示人脸详情
      this.isDetailShow = true;
      this.editType = "show";
      this.row = { ...item };
    },
    handleEdit(item) {
      this.isDetailShow = true;
      this.editType = "edit";
      this.row = { ...item };
    },
    beforeUpload(file) {
      console.log("file", file);
      if (!this.isValidImageType(file.type) || !file.type) {
        return false;
      }
    },
    // 检查文件类型是否符合要求
    isValidImageType(type) {
      const validTypes = ["image/jpeg", "image/png", "image/bmp", "image/tiff"];
      return validTypes.includes(type);
    },
    progressAnimation() {
      const timer = setInterval(() => {
        this.uploadProgress += 10;
        if (this.uploadProgress >= 100) {
          this.uploadProgress = 100;
          clearInterval(timer);
        }
      }, 20);
    },
    async getList() {
      const params = {
        lib_id: this.lib_id,
        qry_len: this.qry_len,
        start_no: this.start_no,
        ...this.formData,
      };
      const res = await getList(params);
      this.tableData = res.data.record;
      this.total_num = res.data.total_num;
    },
    handleExportAll() {
      this.getList();
      this.isBatchExportShow = true;
    },
    handleExport() {
      if (!this.selectedList.length) {
        this.$message.warning(this.$t("face_noChoose"));
        return;
      }
      this.isSingleExportShow = true;
    },
    async confirmSingle(form) {
      if (this.singleStep === 1) {
        this.isSingleExportShow = false;
        this.zippasswd = "";
        this.singleStep = 0;
        return;
      } else {
        const { curuser_pwd } = form;
        const res = await validatePwd({ userpasswd: curuser_pwd });
        if (res.code === 0) {
          const params = {
            img_ids: this.selectedList
              .map((item) => item.vehicle_number)
              .join(","),
            lib_id: this.lib_id,
          };
          const res = await exportList(params);
          this.singleStep = 1;
          this.zippasswd = res.data.zippasswd;
          downLoadUrl(res.data.export_url);
        }
      }
    },
    cancelSingle() {
      this.singleStep = 0;
      this.zippasswd = "";
    },
    cancelBatch() {
      this.batchStep = 0;
      this.zippasswd = "";
    },
    async confirmBatch(form) {
      // 验证密码
      if (this.batchStep === 0) {
        const { curuser_pwd } = form;
        const res = await validatePwd({ userpasswd: curuser_pwd });
        if (res.code === 0) {
          this.batchStep = 1;
        }
      } else {
        const params = {
          lib_id: this.lib_id,
          ...form,
          ...this.formData,
        };
        const res = await exportBatchList(params);
        if (res.code === 0) {
          this.zippasswd = res.data.zippasswd;
          downLoadUrl(res.data.export_url);
        }
      }
    },
    handleDeleteMultiple() {
      if (!this.selectedList.length) {
        this.$message.warning(this.$t("face_noChoose"));
        return;
      }
      this.$confirm(
        this.$t("face_batchDelete", { num: this.selectedList.length }),
        this.$t("batchDelete"),
        {
          confirmButtonText: this.$t("makeSure2"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      ).then(async () => {
        const params = {
          img_ids: this.selectedList.map((item) => item.img_id).join(","),
          lib_id: this.lib_id,
        };
        const res = await deleteList(params);
        if (res.code === 0) {
          util.msg.success("deleteSuccess");
          this.getList();
        }
      });
    },
    handleDelete(row) {
      this.$confirm(
        this.$t("vehicle_del_notice"),
        this.$t("vehicle_del_detail"),
        {
          confirmButtonText: this.$t("makeSure2"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      ).then(async () => {
        const params = {
          lib_id: row.lib_id,
          vehicle_number: row.vehicle_number,
        };
        const res = await deleteSingle(params);
        if (res.code === 0) {
          util.msg.success("deleteSuccess");
          this.getList();
        }
      });
    },
    handleSelectAll() {
      this.tableData.forEach((row) => {
        this.$refs.multipleTable.$refs.selfTable.toggleRowSelection(row);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.parent {
  font-size: 14px;
  height: 100%;
  background: #ffffff;
  border-radius: 20px;
  width: 100%;
  padding: 20px;
  .title {
  }
  .content {
    .card-wrapper {
      flex-wrap: wrap;
    }
  }
  .divider {
    width: 100%;
    height: 2px;
    background-color: rgba(217, 222, 229, 1);
    margin-top: 30px;
    margin-bottom: 30px;
    flex-shrink: 0;
  }
}
</style>
